<script setup>
import { ref, onMounted } from 'vue'
import { ElNotification, ElMessage } from 'element-plus'
import { FlightApi } from '@/api/flight'
import { Search, Refresh } from '@element-plus/icons-vue'
import axios from 'axios'

// 搜索条件
const searchQuery = ref({ cfno: '', cftp: '' })

// 数据状态
const tableData = ref([])
const loading = ref(false)
const pagination = ref({ currentPage: 1, pageSize: 10, total: 0 })

// 获取数据
const fetchData = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.value.currentPage,
      pageSize: pagination.value.pageSize
    }

    let response
    if (searchQuery.value.cfno) {
      response = await FlightApi.getPlanesByAircraftId(searchQuery.value.cfno, params.page, params.pageSize)
    } else if (searchQuery.value.cftp) {
      response = await FlightApi.getPlanesByAircraftType(searchQuery.value.cftp, params.page, params.pageSize)
    } else {
      response = await FlightApi.getFlightPlanes(params.page, params.pageSize)
    }

    if (response && response.data) {
      tableData.value = response.data || []
      pagination.value.total = response.totalRecords || 0
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElNotification.error({
      title: '错误',
      message: '获取数据失败: ' + (error.message || '未知错误')
    })
  } finally {
    loading.value = false
  }
}

// 状态标签类型
const getStatusType = (status) => {
  if (!status) return 'success'
  const statusStr = status.toString().toLowerCase()
  switch (statusStr) {
    case '延误':
      return 'warning'
    case '取消':
      return 'danger'
    case 'onr':
      return 'info'
    case 'delayed':
      return 'warning'
    case 'cancelled':
      return 'danger'
    default:
      return 'success'
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.value.currentPage = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  searchQuery.value = { cfno: '', cftp: '' }
  handleSearch()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.value.pageSize = size
  pagination.value.currentPage = 1
  fetchData()
}

const handleCurrentChange = (page) => {
  pagination.value.currentPage = page
  fetchData()
}

// 调用后端更新接口
const updateFlightPlaneInfo = async (flightData) => {
  // 非空校验
  if (!flightData.flno || !flightData.cfno || !flightData.cftp || !flightData.stat) {
    ElMessage.warning('所有字段都必须填写')
    return
  }

  try {
    await axios.put('http://localhost:8081/flightUpdate/updateplanes', flightData)
    ElNotification.success({
      title: '成功',
      message: '航班信息更新成功'
    })
  } catch (error) {
    console.error('更新失败:', error)
    ElNotification.error({
      title: '错误',
      message: '更新失败，请检查输入或网络连接'
    })
    throw error
  }
}

// 编辑弹窗相关
const dialogVisible = ref(false)
const editableRow = ref({})

// 打开编辑对话框
const handleEdit = (row) => {
  editableRow.value = {
    flno: row.FLNO,
    cfno: row.cfno,
    cftp: row.CFTP,
    stat: row.STAT
  }
  dialogVisible.value = true
}

// 提交编辑
const submitEdit = async () => {
  try {
    await updateFlightPlaneInfo(editableRow.value)
    dialogVisible.value = false
    fetchData() // 刷新表格
  } catch (e) {
    ElMessage.error('保存失败，请检查输入')
  }
}

// 初始化加载数据
onMounted(() => {
  fetchData()
})
</script>

<template>
  <div class="flight-info-container">
    <el-card shadow="hover" class="main-card">
      <template #header>
        <div class="card-header">
          <div class="header-wrapper">
            <h2 class="header-title">航班飞机信息管理</h2>
            <div class="search-bar">
              <el-input
                v-model="searchQuery.cfno"
                placeholder="请输入飞机编号"
                clearable
                class="search-input"
                @keyup.enter="handleSearch"
              >
                <template #prefix>
                  <el-icon>
                    <Search />
                  </el-icon>
                </template>
              </el-input>
              <el-input
                v-model="searchQuery.cftp"
                placeholder="请输入飞机机型"
                clearable
                class="search-input"
                @keyup.enter="handleSearch"
              >
                <template #prefix>
                  <el-icon>
                    <Search />
                  </el-icon>
                </template>
              </el-input>
              <el-button type="primary" @click="handleSearch" class="action-button">
                <el-icon><Search /></el-icon>
                查询
              </el-button>
              <el-button @click="resetSearch" class="action-button">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </div>
          </div>
        </div>
      </template>

      <div class="table-container">
        <el-table
          :data="tableData"
          border
          stripe
          v-loading="loading"
          style="width: 100%"
          empty-text="暂无数据"
          highlight-current-row
        >
          <el-table-column prop="FLNO" label="航班号" min-width="120" align="center" />
          <el-table-column prop="cfno" label="飞机编号" min-width="120" align="center" />
          <el-table-column prop="CFTP" label="飞机机型" min-width="120" align="center" />
          <el-table-column prop="STAT" label="状态" min-width="120" align="center">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.STAT)" effect="light">
                {{ row.STAT || '正常' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            v-if="$store.getters.currentRole === 'admin'"
            label="操作"
            width="120"
            align="center"
            fixed="right"
          >
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button
                  type="primary"
                  size="small"
                  @click="handleEdit(row)"
                  plain
                >
                  编辑
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            class="right-pagination"
          />
        </div>
      </div>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog v-model="dialogVisible" title="编辑航班信息" width="40%">
      <el-form :model="editableRow" label-width="100px">
        <el-form-item label="航班号">
          <el-input v-model="editableRow.flno" placeholder="例如：CA1234" />
        </el-form-item>
        <el-form-item label="飞机编号">
          <el-input v-model="editableRow.cfno" placeholder="例如：B738-1234" />
        </el-form-item>
        <el-form-item label="飞机机型">
          <el-input v-model="editableRow.cftp" placeholder="例如：B738" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="editableRow.stat" placeholder="请选择状态" style="width: 100%">
            <el-option label="正常" value="正常" />
            <el-option label="延误" value="延误" />
            <el-option label="取消" value="取消" />
            <el-option label="ONR" value="ONR" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false" class="action-button">取 消</el-button>
          <el-button type="primary" @click="submitEdit" class="action-button">保 存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.flight-info-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 64px);
}

.main-card {
  border-radius: 8px;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-header {
  width: 100%;
}

.header-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.header-title {
  margin: 0;
  font-size: 18px;
  color: var(--el-text-color-primary);
  white-space: nowrap;
}

.search-bar {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  justify-content: flex-end;
}

.search-input {
  width: 200px;
}

.action-button {
  white-space: nowrap;
}

.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  position: relative;
}

.el-table {
  flex: 1;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
  background: #fff;
  border-top: 1px solid var(--el-border-color-light);
  position: sticky;
  bottom: 0;
  z-index: 1;
}

.right-pagination {
  display: flex;
  justify-content: flex-end;
  width: 100%;
}

.right-pagination :deep(.el-pagination__total),
.right-pagination :deep(.el-pagination__sizes),
.right-pagination :deep(.el-pagination__jump) {
  margin-left: 10px;
}

.action-buttons {
  display: flex;
  justify-content: center;
}

.dialog-footer {
  text-align: right;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .search-bar {
    gap: 8px;
  }
  .search-input {
    width: 150px;
  }
}

@media (max-width: 992px) {
  .header-wrapper {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .search-bar {
    width: 100%;
    justify-content: flex-start;
  }

  .search-input {
    width: calc(50% - 5px);
  }

  .action-button {
    flex: 1;
  }
}

@media (max-width: 768px) {
  .pagination-container {
    width: 100%;
    overflow-x: auto;
  }

  .right-pagination {
    flex-wrap: wrap;
    justify-content: flex-end;
  }

  .right-pagination :deep(.el-pagination__total),
  .right-pagination :deep(.el-pagination__sizes),
  .right-pagination :deep(.el-pagination__jump) {
    margin: 5px 0;
    width: 100%;
    justify-content: flex-end;
  }

  .el-table-column {
    min-width: 100px !important;
  }
}

@media (max-width: 576px) {
  .flight-info-container {
    padding: 10px;
  }

  .search-input {
    width: 100%;
  }

  .action-button {
    width: 100%;
  }

  .right-pagination :deep(.btn-prev),
  .right-pagination :deep(.btn-next),
  .right-pagination :deep(.more) {
    display: none;
  }
}
</style>
